/*
 * This will find the given ascii movie file in folder and then start playing it
 * frame by frame.
 *
 * I am only using this to test that I can make a working player.
 *
 * Also I may later make the framerate adjustable
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>

#define MAX_FRAME	10000
#define MAX_LINE	300
#define NAME_MAX	100
#define FRAME_RATE	100000 // frame rate in micro seconds

int main(void)
{
	int endOfFrame, eofFlag;
	char frame[MAX_FRAME];
	char temp[MAX_LINE];
	char textEnd[] = ".txt";
	char fileBegin[] = "./";
	char theFile[] = "walk";
	char fileName[NAME_MAX];
	FILE *movieFile;
	
	/* open the file */
	strcpy(fileName, fileBegin);
	strcat(fileName, theFile);
	strcat(fileName, textEnd);
	printf("The new file name is '%s'\n", fileName);
	
	if ((movieFile = fopen(fileName, "r")) == NULL)
	{
		perror("opening file");
		exit(EXIT_FAILURE);
	}
	else
	{
		eofFlag = 0;
		while (eofFlag == 0)
		{
			printf("\033[2J");
			printf("\033[0;0f");
			frame[0] = '\0';
			endOfFrame = 0;
			while (endOfFrame == 0)
			{
				/* read a line */
				if (fgets(temp, MAX_LINE + 1, movieFile) == (char *) NULL)
				{
					/* if it's the end of the file, set the eofFlag */
					printf("End of file reached\n");
					eofFlag++;
					break;
				}
				else
				{
					/* if it's "end" set a flag, otherwise add to frame */
					if (strncmp(temp, "end", 3) == 0)
					{
						endOfFrame++;
					}
					else
					{
						strncat(frame, temp, strlen(temp));
					}
				}
			}
			/* show what you read */
			printf("%s", frame);
			usleep(FRAME_RATE);
		}
		
		/* close the file */
		if (fclose(movieFile))
		{
			perror("closing file");
			exit(EXIT_FAILURE);
		}
	}	
	return 0;
}
